<template>
  <el-card class="">
    <div style="margin: 10px 0" class="flex items-center">
      <el-input clearable style="width: 200px" prefix-icon="Search" placeholder="请输入名称" suffix-icon="el-icon-search"
        v-model="queryData.name"></el-input>
      <el-button class="bg-blue-500" type="primary" @click="initData()">搜索</el-button>
    </div>
    <el-button type="primary" class=" bg-green-600" @click="handleAdd(null)">添加角色 <i
        class="el-icon-circle-plus-outline"></i></el-button>
  </el-card>

  <el-card class="mt10">
    <div style="margin: 10px 0">
      <el-popconfirm class="ml-5" confirm-button-text='确定' cancel-button-text='我再想想' icon="el-icon-info" icon-color="red"
        title="您确定批量删除这些数据吗？" @confirm="delBatch">
        <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
    </div>
    <el-table :data="tableData.list" border stripe :header-cell-class-name="'headerBg'" row-key="id" default-expand-all
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="序号" width="100"></el-table-column>
      <el-table-column prop="roleKey" label="名称" width="150"></el-table-column>
      <el-table-column prop="name" label="描述" width="150"></el-table-column>
      <el-table-column label="创建时间">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-icon>
              <timer />
            </el-icon>
            <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === '1' ? 'error' : 'success'" disable-transitions>{{
            showStatus(scope.row.status)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template #default="scope">
          <el-button type="info" class=" bg-blue-500" @click="selectMenu(scope.row)">分配菜单 <i
              class="el-icon-menu"></i></el-button>
          <el-button type="success" class=" bg-green-500" @click="handleEdit(scope.row)">编辑 <i
              class="el-icon-edit"></i></el-button>
          <el-popconfirm class="ml-5" confirm-button-text='确定' cancel-button-text='我再想想' icon="el-icon-info"
            icon-color="red" title="您确定删除吗？" @confirm="handleDelRole(scope.row.id)">
            <template #reference>
              <el-button type="danger" class=" bg-red-600" slot="reference">删除 <i
                  class="el-icon-remove-outline"></i></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class=" mt-4" style="margin-left: 70%;" background v-model:current-page="queryData.currentPage"
      v-model:page-size="queryData.pageSize" :page-sizes="[10, 20, 30, 40]" small="small"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </el-card>
  <el-dialog title="角色" v-model="dialogFormVisible" width="30%" :before-close="handleClose">
    <el-form label-width="80px" size="small">
      <el-form-item v-if="isUpdate" label="序号">
        <el-input disabled v-model="editData.form.id" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="editData.form.roleKey" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="editData.form.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="editData.form.status">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" class=" bg-blue-500" @click="confirmEdit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog title="菜单分配" v-model="menuDialogVis" width="30%" :before-close="handleClose">
    <el-tree :props="props" :data="menuData.list" show-checkbox node-key="id" ref="treeRef"
      :default-expanded-keys="expends.list" :default-checked-keys="checks.list">
      <template class="custom-tree-node" #default="{ node, data }">
        <span><i :class="data.icon"></i> {{ data.title }}</span>
      </template>
    </el-tree>
    <template #footer class="dialog-footer">
      <el-button @click="menuDialogVis = false">取 消</el-button>
      <el-button type="primary" class="bg-blue-500" @click="saveRoleMenu">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import {
  getRoleList, updateRole, deleteRole,
  getRoleMenuById, getIds, insertRoleMenu
} from '../../../api/modules/role';
import { getMenuList } from '../../../api/modules/menu';
import { ElNotification, ElMessageBox } from 'element-plus';
const tableData = reactive({
  list: []
})
const menuData = reactive({
  list: []
})
const expends = reactive({
  list: []
})
const checks = reactive({
  list: []
})
const isUpdate = ref(true)
const dialogFormVisible = ref(false)
const total = ref('')
const queryData = reactive({
  currentPage: 1,
  pageSize: 10,
  name: ''
})
const ids = reactive({
  list: []
})
const props = {
  label: 'name',
}
const menuDialogVis = ref(false)
const initData = async () => {
  let res = await getRoleList(queryData)
  tableData.list = res.data.data.records
  total.value = res.data.data.total
}
const initIds = async () => {
  let res = await getIds();
  console.log(res);
  ids.list = res.data.data
}
const treeRef = ref()
const selectMenu = async (item) => {
  roleId.value = item.id
  menuDialogVis.value = true
  let res = await getMenuList(queryData)
  menuData.list = res.data.data.records
  expends.list = menuData.list.map(v => v.id)
  let roleMenu = await getRoleMenuById(item.id)
  checks.list = roleMenu.data.data
  ids.list.forEach(id => {
    if (!checks.list.includes(id)) {
      nextTick(() => {
        treeRef.value.setChecked(id, false)
      })
    }
  })
}
const roleId = ref('')
const saveRoleMenu = async () => {
  let data = {
    roleId: roleId.value,
    menuList: treeRef.value.getCheckedKeys()
  }
  let res = await insertRoleMenu(data)
  if (res.data.data === true) {
    ElNotification.success("绑定成功")
    menuDialogVis.value = false
  } else {
    ElNotification.success("绑定失败")
  }
}
const handleClose = (done) => {
  ElMessageBox.confirm('您确定关闭对话框吗？')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}
const icons = [
  'User', 'House', 'MessageBox', 'Menu', 'Grid',
  'Avatar', 'List', 'DeleteFilled', 'Connection',
  'Star', 'Clock', 'HomeFilled', 'CreditCard', 'Calendar',
  'Refrigerator', 'Money', 'Present', 'HelpFilled'
]
const showStatus = (status) => {
  if (status == '0') {
    return "正常"
  } else {
    return "停用"
  }
}
const handleAdd = () => {
  isUpdate.value = false
  dialogFormVisible.value = true
  editData.form = {}
}
let editData = reactive({
  form: {}
})
const confirmEdit = async () => {
  let res = await updateRole(editData.form)
  if (res.data.data > 0) {
    ElNotification.success("操作成功")
    initData()
    dialogFormVisible.value = false
  } else {
    ElNotification.error("操作失败")
  }
}
const handleEdit = (data) => {
  dialogFormVisible.value = true
  editData.form = data
  isUpdate.value = true
}
const handleDelRole = async (id) => {
  let res = await deleteRole(id)
  if (res.data.data > 0) {
    ElNotification.success("删除成功")
    initData()
  } else {
    ElNotification.error("删除失败")
  }
}
const handleSizeChange = (val) => {
  queryData.pageSize = val
  initData()
}
const handleCurrentChange = (val) => {
  queryData.currentPage = val
  initData()
}
onMounted(() => {
  initData()
  initIds()
})

</script>


<style>
.headerBg {
  background: #eee !important;
}
</style>
